package com.suneee.cloud.erpInterface.util;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.suneee.base.config.ServiceConfig;
import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.HttpClientUtils;
import com.suneee.base.util.JsonUtil;
import com.suneee.cloud.erpInterface.bean.CategoryBean;
import com.suneee.cloud.erpInterface.bean.ProductBean;
import com.suneee.cloud.erpInterface.bean.ResultBean;
import com.suneee.cloud.erpInterface.service.ErpProductService;
import com.suneee.cloud.erpInterface.service.OrderService;
import com.suneee.core.type.json.JsonUtils;
import com.suneee.core.util.DateUtils;
import com.suneee.trades.entity.TradesInfo;

@Component
public class ErpTask {
	private static final Logger logger = LoggerFactory.getLogger(ErpTask.class);
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ErpProductService  erpProductService;
	
	public Map<String,Object> map = new HashMap<String, Object>();
	
	
	/**
	 * 定时拉取ERP类目信息
	 */
	public void queryCategoryInfo(){
	
		String erpUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getErpUrl();
		
		CategoryBean bean = new CategoryBean();
		Object obj = bean;
		try {
			String json = JsonUtils.writer().writeValueAsString(obj);
			String resultInfo= HttpClientUtils.postJson("", json,erpUrl); //调用接口发送商品信息
			
			Map<String,Object> resultMap  = (Map<String, Object>) JsonUtil.fromJson(resultInfo, map.getClass());
			
			List<CategoryBean> categoryList = (List<CategoryBean>) resultMap.get("categoryList");
			boolean isFlag = erpProductService.getErpCategoryInfo(categoryList);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void sendOrderInfo(){
		logger.info("发送订单信息到ERP系统开始："+DateUtils.formatDateTime(new Date()));
		String erpUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getErpUrl();
//		List<OrderBean> orderList =orderService.sendOrderInfo();
		
		List<TradesInfo> tradesList = orderService.sendOrderInfo();
		
		//1.一次请求处理， 发送20份数据。
		//2.两次请求的最短时间间隔50ms
		if(tradesList != null && tradesList.size() >0){
			int total = tradesList.size();
			int pageNum =  total / 20 + (total % 20 == 0 ? 0 : 1); 
			for (int i = 1; i <= pageNum; i++) {
				if(i*20 < total){
					List<TradesInfo>  newlist = tradesList.subList((i-1)*20,i*20);
					this.sendOrderInfoInf(newlist, erpUrl);
				}else{
					List<TradesInfo>  newlist = tradesList.subList((i-1)*20,total);
					this.sendOrderInfoInf(newlist, erpUrl);
				}
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}else{
			logger.info("-------------本次同步没有待同步的商品信息-----------"+DateUtils.formatDateTime(new Date()));
		}
		logger.info("发送订单信息到ERP系统结束："+DateUtils.formatDateTime(new Date()));
		
	}
	
	@SuppressWarnings("unchecked")
	public void sendOrderInfoInf(List<TradesInfo>  newlist,String erpUrl){
		
		ResultBean bean = new ResultBean();
		bean.setOrders(newlist);
		Object obj = bean;
		try {
			String json = JsonUtils.writer().writeValueAsString(obj);
			logger.info("订单同步到商城,data="+json);
			String resultInfo= HttpClientUtils.postJson("", json,erpUrl); //调用接口发送商品信息
			logger.info("ERP接口调用返回信息："+resultInfo);
			Map<String,Object> resultMap  = (Map<String, Object>) JsonUtil.fromJson(resultInfo, map.getClass());
			Integer code = (Integer) resultMap.get("code");
			if(code == 200){
				logger.info("订单推送接口调用成功......");
			}else{
				logger.error("订单推送接口调用出错："+resultInfo);
			}
			
		} catch (Exception e) {
			logger.error("订单推送接口出错："+e.getMessage());
		}
		
	}
	
	/**
	 * 定时同步ERP商品信息
	 */
	@SuppressWarnings("unchecked")
	public void queryErpProductInfo(){
		String erpUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getErpUrl();
//		bean.setSpuId("");
		ProductBean bean = new ProductBean();
		Object obj = bean;
		try {
			String json = JsonUtils.writer().writeValueAsString(obj);
			String resultInfo= HttpClientUtils.postJson("", json,erpUrl); //调用接口发送商品信息
			logger.info("ERP接口调用返回信息："+resultInfo);
			Map<String,Object> resultMap  = (Map<String, Object>) JsonUtil.fromJson(resultInfo, map.getClass());
			Integer code = (Integer) resultMap.get("code");
			if(code == 200){
				//获取传输过来的商品集合
				List<ProductBean> list = (List<ProductBean>) resultMap.get("productList");
				
				if(list != null && list.size() > 0){
					erpProductService.getErpProductInfo(list);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void taskInfo(){
		this.sendOrderInfo();//发送订单信息
		this.queryErpProductInfo();//定时同步商品信息
	}
}
